package com.naicheng.ivote.engin;

import java.util.HashMap;

import org.json.JSONObject;

import com.naicheng.ivote.constant.ConstantMine;
import com.naicheng.ivote.doman.BaseRequestBean;
import com.naicheng.ivote.volley.Request;
import com.naicheng.ivote.volley.VolleyError;
import com.naicheng.ivote.volley.Response.ErrorListener;
import com.naicheng.ivote.volley.Response.Listener;
import com.naicheng.ivote.volley.toolbox.JsonObjectRequest;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

public abstract class BaseFragment extends Fragment{
	
	public static final String TAG = BaseFragment.class.getSimpleName();
	
	protected FragmentActivity CTX ;
	protected View mViewRoot;
	protected LayoutInflater inflater;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		this.inflater = inflater;
		mViewRoot = initViews(inflater, container, savedInstanceState);
		init();
		return mViewRoot;
	}
	
	
	
	protected void init() { }



	protected abstract View initViews(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState);

	@SuppressWarnings("unchecked")
	protected <T extends View> T getView(int resID) {
		if( mViewRoot == null){
			return null;
		}
		return(T)mViewRoot.findViewById(resID);
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		CTX = getActivity();
	}
	
	/**
	 * 网络请求
	 * @param requestcommand
	 * @param map
	 * @param listener
	 * @param context
	 */
	public static void getDataFromServer(String requestcommand,
			HashMap<String, String> map, Listener<JSONObject> listener,final Context context) {
		
		ErrorListener errorListener = new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				Toast.makeText(context, "网络异常", Toast.LENGTH_LONG).show();
			}
		};

		BaseRequestBean bean = new BaseRequestBean(requestcommand);
		if (map == null) {
			map = new HashMap<String, String>();
		}
		map.putAll(bean.toMap());
		JsonObjectRequest jor = new JsonObjectRequest(Request.Method.POST, ConstantMine.url,
				new JSONObject(map), listener, errorListener);
		MyRequestQueen.getQueenInstance(context).addTask(jor);
	}
}
